﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WcfContrib.Extensions.Caching
{
    /// <summary>
    /// Represents description for output cache interval
    /// </summary>
    public class OutputCacheInterval
    {
        /// <summary>
        /// Gets or sets the cache policy.
        /// </summary>
        /// <value>The cache policy.</value>
        public OutputCachePolicy Policy { get; set; }
        /// <summary>
        /// Gets or sets the time interval.
        /// </summary>
        /// <value>The time interval.</value>
        public TimeSpan Interval { get; set; }

        /// <summary>
        /// Gets or sets the time the item was last retrieved at.
        /// </summary>
        /// <value>The time the item was last retrieved at.</value>
        public DateTime LastVisitedAt { get; set; }
        /// <summary>
        /// Gets or sets the time the item was last added at.
        /// </summary>
        /// <value>The time the item was last added at.</value>
        public DateTime AddedAt { get; set; }

        /// <summary>
        /// Clones this instance for handling with the cache provider.
        /// </summary>
        /// <returns>The cloned OutputCacheInterval</returns>
        public OutputCacheInterval CloneCore()
        {
            return new OutputCacheInterval
            {
                Policy = Policy,
                Interval = Interval
            };
        }

        /// <summary>
        /// Determines whether this interval description is valid for the current time.
        /// </summary>
        /// <returns>
        /// 	<c>true</c> if this interval description is valid for the current time; otherwise, <c>false</c>.
        /// </returns>
        public bool IsActive()
        {
            DateTime mark = DateTime.Now;

            if (Policy == OutputCachePolicy.Absolute)
            {
                return mark.Subtract(Interval) <= AddedAt;
            }
            else if (Policy == OutputCachePolicy.Sliding)
            {
                return mark.Subtract(Interval) <= LastVisitedAt;
            }

            return false;
        }
    }
}
